// 财联社电报展示页面JavaScript逻辑

// 全局变量
let refreshInterval = null;
let currentIntervalTime = 60000; // 默认60秒

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 初始化页面
    initializePage();
    
    // 绑定事件
    bindEvents();
    
    // 首次加载数据
    loadTelegrams();
    loadStats();
    
    // 启动定时刷新
    startAutoRefresh();
});

// 初始化页面
function initializePage() {
    console.log('初始化财联社电报展示页面');
}

// 绑定事件
function bindEvents() {
    // 刷新按钮
    const refreshBtn = document.getElementById('refresh-btn');
    if (refreshBtn) {
        refreshBtn.addEventListener('click', function() {
            manualRefresh();
        });
    }
    
    // 刷新间隔选择
    const intervalSelect = document.getElementById('refresh-interval');
    if (intervalSelect) {
        intervalSelect.addEventListener('change', function() {
            changeRefreshInterval(this.value);
        });
    }
    
    // 显示数量选择
    const countSelect = document.getElementById('display-count');
    if (countSelect) {
        countSelect.addEventListener('change', function() {
            loadTelegrams();
        });
    }
}

// 手动刷新
function manualRefresh() {
    console.log('手动刷新数据');
    loadTelegrams();
    loadStats();
    updateLastRefreshTime();
}

// 改变刷新间隔
function changeRefreshInterval(seconds) {
    const milliseconds = parseInt(seconds) * 1000;
    currentIntervalTime = milliseconds;
    
    // 重新启动定时器
    stopAutoRefresh();
    startAutoRefresh();
    
    console.log(`刷新间隔已更改为 ${seconds} 秒`);
}

// 启动自动刷新
function startAutoRefresh() {
    if (refreshInterval) {
        clearInterval(refreshInterval);
    }
    
    refreshInterval = setInterval(function() {
        console.log('自动刷新数据');
        loadTelegrams();
        loadStats();
        updateLastRefreshTime();
    }, currentIntervalTime);
    
    console.log(`自动刷新已启动，间隔: ${currentIntervalTime/1000} 秒`);
}

// 停止自动刷新
function stopAutoRefresh() {
    if (refreshInterval) {
        clearInterval(refreshInterval);
        refreshInterval = null;
        console.log('自动刷新已停止');
    }
}

// 更新最后刷新时间
function updateLastRefreshTime() {
    const now = new Date();
    const timeString = now.toLocaleString('zh-CN');
    const lastRefreshElement = document.getElementById('last-refresh');
    if (lastRefreshElement) {
        lastRefreshElement.textContent = `最后刷新: ${timeString}`;
    }
}

// 加载电报数据
function loadTelegrams() {
    const container = document.getElementById('telegrams-container');
    if (!container) return;
    
    // 显示加载状态
    container.innerHTML = '<div class="loading">正在加载数据...</div>';
    
    // 获取显示数量
    const countSelect = document.getElementById('display-count');
    const limit = countSelect ? parseInt(countSelect.value) : 50;
    
    // 发送请求
    fetch(`/api/telegrams?limit=${limit}`)
        .then(response => response.json())
        .then(data => {
            displayTelegrams(data);
            updateLastRefreshTime();
        })
        .catch(error => {
            console.error('加载电报数据失败:', error);
            container.innerHTML = '<div class="error">加载数据失败，请稍后重试</div>';
        });
}

// 显示电报数据
function displayTelegrams(telegrams) {
    const container = document.getElementById('telegrams-container');
    if (!container) return;
    
    if (!telegrams || telegrams.length === 0) {
        container.innerHTML = '<div class="loading">暂无电报数据</div>';
        return;
    }
    
    let html = '';
    telegrams.forEach(telegram => {
        html += createTelegramItem(telegram);
    });
    
    container.innerHTML = html;
}

// 创建单个电报项的HTML
function createTelegramItem(telegram) {
    // 处理阅读数样式
    let readingClass = '';
    if (telegram.reading_num >= 100000) {
        readingClass = 'very-high';
    } else if (telegram.reading_num >= 50000) {
        readingClass = 'high';
    }
    
    // 截取内容
    let content = telegram.content || '';
    if (content.length > 200) {
        content = content.substring(0, 200) + '...';
    }
    
    return `
        <div class="telegram-item">
            <div class="telegram-header">
                <div class="telegram-time">${formatTime(telegram.time)}</div>
            </div>
            <div class="telegram-title">${escapeHtml(telegram.title || '')}</div>
            <div class="telegram-content">${escapeHtml(content)}</div>
            <div class="telegram-meta">
                <div class="reading-count ${readingClass}">阅读: ${telegram.reading_num}</div>
                <a href="${telegram.url}" target="_blank" class="view-link">查看原文 →</a>
            </div>
        </div>
    `;
}

// 格式化时间
function formatTime(timeString) {
    if (!timeString) return '';
    
    try {
        const date = new Date(timeString.replace(' ', 'T'));
        return date.toLocaleString('zh-CN');
    } catch (e) {
        return timeString;
    }
}

// HTML转义
function escapeHtml(text) {
    if (!text) return '';
    const map = {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#039;'
    };
    return text.replace(/[&<>"']/g, function(m) { return map[m]; });
}

// 加载统计数据
function loadStats() {
    fetch('/api/stats')
        .then(response => response.json())
        .then(data => {
            updateStats(data);
        })
        .catch(error => {
            console.error('加载统计数据失败:', error);
        });
}

// 更新统计数据
function updateStats(stats) {
    if (stats.total_count !== undefined) {
        const totalCountElement = document.getElementById('total-count');
        if (totalCountElement) {
            totalCountElement.textContent = `总电报数: ${stats.total_count}`;
        }
    }
    
    if (stats.latest_time) {
        const latestTimeElement = document.getElementById('latest-time');
        if (latestTimeElement) {
            latestTimeElement.textContent = `最新更新: ${formatTime(stats.latest_time)}`;
        }
    }
}

// 页面卸载时清理
window.addEventListener('beforeunload', function() {
    stopAutoRefresh();
});